package cn.source.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONValidator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;

@Slf4j
public class JsonUtil {

    public static String write(Object obj) {
        try {
            return JSON.toJSONString(obj);
        } catch (Exception e) {
            log.warn(String.format("write json toString failed, %s", obj == null ? "null" : obj.getClass().toString()));
            return null;
        }
    }

    public static <T> T read(String jsonStr) {
        try {
            if (jsonStr == null || jsonStr.trim().isEmpty()) {
                return null;
            }
            if (!JSONValidator.from(jsonStr).validate()) {
                log.info("JSONValidator validate failed: {}", jsonStr);
                return null;
            }
            return (T) JSON.parse(jsonStr);
        } catch (Exception e) {
            log.warn(String.format("read json from string failed, %s", jsonStr), e);
            return null;
        }
    }

    public static <T> T read(String jsonStr, Class<T> clazz) {
        if (jsonStr == null || jsonStr.trim().isEmpty() || clazz == null) {
            return null;
        }
        try {
            return JSON.parseObject(jsonStr, clazz);
        } catch (Exception e) {
            log.warn(String.format("read json failed, json: %s, clazz: %s", jsonStr, ObjectUtils.toString(clazz)), e);
            return null;
        }
    }

}
